//
//  HPNetworkingTools.swift
//  MyWeibo
//
//  Created by Apeng on 16/4/11.
//  Copyright © 2016年 Apengpeng. All rights reserved.
//

import UIKit
import AFNetworking

// 定义网络请求枚举
enum NS_HttpMethod: String {
    
    case POST = "POST"
    case GET = "GET"
}

// baseURL
struct API {
    // baseURL
    static let onlineHost = "https://api.weibo.com/"
    // 开发者URL
    static let developHost = "https://api.weibo.devlopment.com/"
    // 获取accessToken的URL
    static let authrizonURLStr = "oauth2/access_token"
    // 获取用户信息的URL
    static let useInfoURLStr = "2/users/show.json"
    static let homepage = "2/statuses/home_timeline.json"
    // 发布微博
    static let sendStatus = "2/statuses/update.json"
    
    static let uplodaImage = "https://upload.api.weibo.com/2/statuses/upload.json"
}

// 单例
class HPNetworkingTools: AFHTTPSessionManager {
    
    // Swift 中实现单例
    static let sharedTools: HPNetworkingTools = {
        let tools = HPNetworkingTools(baseURL: NSURL(string: API.onlineHost))
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
}



// 登陆网络请求, 需返回是否登陆成功
extension HPNetworkingTools {
    
    func getAccessTokenByCode(code: String, finished: (result: AnyObject?, error: NSError?) -> ()) {
        
        // API要求的参数
        let parameters = ["client_id":client_id, "client_secret":client_secret, "grant_type": "authorization_code", "code":code, "redirect_uri":redirect_uri]

        // 在ViewMode 中是调用网络请求工具来发送请求, 通过闭包来返回是否成功
        // 封装在NetWorking类中后直接调用就好
        request(.POST, urlStr: API.authrizonURLStr, parameters: parameters, finished: finished)
    }
}


// 加载"用户信息"的封装
extension HPNetworkingTools {
    func loadUserAccountInfo(token: AnyObject, uid:AnyObject, finished: (result: AnyObject?, error: NSError?) -> ()) {

        // 请求参数
        let paratemers = ["access_token":token, "uid":uid]
        // 发送获取用户信息的网络请求
        request(.GET, urlStr: API.useInfoURLStr, parameters: paratemers, finished: finished)
    }
}


// 加载homePage 页面的数据, 面向接口
extension HPNetworkingTools {
    
    // 给以上的方法增加一个参数, 实现加载更多
    func loadHomePageData(token: String, max_id: Int64,since_id: Int64, finished: (result: AnyObject?, error: NSError?) -> ()) {
        var parmaters = ["access_token":token]
        // 判断
        if max_id > 0 {
            // 修改值
            parmaters["max_id"] = "\(max_id - 1)" // - 1 解决数据重复的问题
        }
        
        if since_id > 0 {
            
            parmaters["since_id"] = "\(since_id)"
        }
        
        request(.GET, urlStr: API.homepage, parameters: parmaters, finished: finished)
    }
}


// MARK: 发布微博
extension HPNetworkingTools {
    
    func sendStatus(token: String, status: String, imageList: [UIImage] = [UIImage](),finished:(result: AnyObject?, error: NSError?) -> ()) {
        
        let parameters = ["access_token":token, "status":status]
        
        // 判断是否有图片
        if imageList.count > 0 {
            // 发布图片, 上传图片, 使用post请求
            POST(API.uplodaImage, parameters: parameters, constructingBodyWithBlock: { (formdata
                ) -> Void in
                // 件上面的二进制数据添加到formdata
                }, progress: nil, success: { (_, result) -> Void in
                    finished(result: result, error: nil)
                }, failure: { (_, error) -> Void in
                    finished(result: nil, error: error)
            })
            
        } else { // 发布文本微博
            
            request(.POST, urlStr: API.sendStatus, parameters: parameters, finished: finished)
        }
    }
}


// 封装网络请求的方法
extension HPNetworkingTools {
    
    func request(method: NS_HttpMethod, urlStr: String, parameters: AnyObject?, finished: (result: AnyObject?, error: NSError?) -> ()) {
        
        // 定义闭包, 返回值为空  (参数) -> (返回值) in  闭包的基本格式, 返回值为空时 可以写 Void in
        let success = {(task: NSURLSessionDataTask, result: AnyObject?) -> () in
            finished(result: result, error: nil)
        }
        
        let failure = {(task:NSURLSessionDataTask?, error: NSError) -> () in
            finished(result: nil, error: error)
        }
        
        if method == .GET {
            
            GET(urlStr, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            POST(urlStr, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
    
}
